<?php
class M_Images extends Model{
	
	public $bgcolor = "#FFFFFF";
	
	/**
	 * 裁剪图片
	 * @author gjw
	 *
	 * @param unknown $im
	 * @param unknown $target_width
	 * @param unknown $target_height
	 * @param unknown $name
	 * @param unknown $source_mime
	 */
	function imagecropper($im, $target_width, $target_height, $name, $source_mime)
	{
		$source_width = imagesx($im);
		$source_height = imagesy($im);
		$source_ratio  = $source_height / $source_width;
		$target_ratio  = $target_height / $target_width;
	
		// 源图过高
		if ($source_ratio > $target_ratio)
		{
			$cropped_width  = $source_width;
			$cropped_height = $source_width * $target_ratio;
			$source_x = 0;
			$source_y = ($source_height - $cropped_height) / 2;
		}
		// 源图过宽
		elseif ($source_ratio < $target_ratio)
		{
			$cropped_width  = $source_height / $target_ratio;
			$cropped_height = $source_height;
			$source_x = ($source_width - $cropped_width) / 2;
			$source_y = 0;
		}
		// 源图适中
		else
		{
			$cropped_width  = $source_width;
			$cropped_height = $source_height;
			$source_x = 0;
			$source_y = 0;
		}
	
		$target_image  = imagecreatetruecolor($target_width, $target_height);
		$cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
	
		// 裁剪
		imagecopy($cropped_image, $im, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
		// 缩放
		imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
		if($source_mime=="png"){
			imagepng($target_image, $name);
		}else if($source_mime=="jpeg"){
			imagejpeg($target_image, $name);
		}else if($source_mime=="gif"){
			imagegif($target_image, $name);
		}
		imagedestroy($target_image);
		imagedestroy($cropped_image);
	}
	
	/**
	 * 缩放图片
	 * @param unknown $im
	 * @param unknown $maxwidth
	 * @param unknown $maxheight
	 * @param unknown $name
	 * @param unknown $filetype
	 */
	public function resizeImage($im, $maxwidth, $maxheight, $name, $imge_type){
		$pic_width = imagesx($im);
		$pic_height = imagesy($im);
		$resizewidth_tag = $resizeheight_tag = false;
		if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)){
			if($maxwidth && $pic_width>$maxwidth)
			{
				$widthratio = $maxwidth/$pic_width;
				$resizewidth_tag = true;
			}
				
			if($maxheight && $pic_height>$maxheight)
			{
				$heightratio = $maxheight/$pic_height;
				$resizeheight_tag = true;
			}
				
			if($resizewidth_tag && $resizeheight_tag)
			{
				if($widthratio<$heightratio){
					$ratio = $widthratio;
				}else{
					$ratio = $heightratio;
				}
			}
				
			if($resizewidth_tag && !$resizeheight_tag){
				$ratio = $widthratio;
			}
				
			if($resizeheight_tag && !$resizewidth_tag){
				$ratio = $heightratio;
			}
				
			$newwidth = $pic_width * $ratio;
			$newheight = $pic_height * $ratio;
				
			if(function_exists("imagecopyresampled"))
			{
				$newim = imagecreatetruecolor($newwidth,$newheight);//PHP系统函数
				imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP系统函数
			}
			else
			{
				$newim = imagecreate($newwidth,$newheight);
				imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
			}
			if($imge_type=="png"){
				imagepng($newim, $name);
			}else if($imge_type=="jpeg"){
				imagejpeg($newim, $name);
			}else if($imge_type=="gif"){
				imagegif($newim, $name);
			}
			imagedestroy($newim);
		}else{
				
			if($imge_type=="png"){
				imagepng($im, $name);
			}else if($imge_type=="jpeg"){
				imagejpeg($im, $name);
			}else if($imge_type=="gif"){
				imagegif($im, $name);
			}
		}
	}
	
 /**
     * 创建图片的缩略图 ==原图不变
     *
     * @access  public
     * @param   string      $img    原始图片的路径
     * @param   int         $thumb_width  缩略图宽度
     * @param   int         $thumb_height 缩略图高度
     * @param   strint      $path         指定生成图片的目录名
     * @return  mix         如果成功返回缩略图的路径，失败则返回false
     */
    function make_thumb($img, $thumb_width = 0, $thumb_height = 0, $path = '', $bgcolor='')
    {
    	 $gd = $this->gd_version(); //获取 GD 版本。0 表示没有 GD 库，1 表示 GD 1.x，2 表示 GD 2.x
         if ($gd == 0)
         {
            // $this->error_msg = $GLOBALS['_LANG']['missing_gd'];
             return false;
         }

        /* 检查缩略图宽度和高度是否合法 */
        if ($thumb_width == 0 && $thumb_height == 0)
        {
            return str_replace(SHOP_PATH, '', str_replace('\\', '/', realpath($img)));
        }

        /* 检查原始文件是否存在及获得原始文件的信息 */
        $org_info = @getimagesize($img);
        if (!$org_info)
        {
           // $this->error_msg = sprintf($GLOBALS['_LANG']['missing_orgin_image'], $img);
          //  $this->error_no  = ERR_IMAGE_NOT_EXISTS;

            return false;
        }

        if (!$this->check_img_function($org_info[2]))
        {
          //  $this->error_msg = sprintf($GLOBALS['_LANG']['nonsupport_type'], $this->type_maping[$org_info[2]]);
        //    $this->error_no  =  ERR_NO_GD;

            return false;
        }

        $img_org = $this->img_resource($img, $org_info[2]);

        /* 原始图片以及缩略图的尺寸比例 */
        $scale_org      = $org_info[0] / $org_info[1];
        /* 处理只有缩略图宽和高有一个为0的情况，这时背景和缩略图一样大 */
        if ($thumb_width == 0)
        {
            $thumb_width = $thumb_height * $scale_org;
        }
        if ($thumb_height == 0)
        {
            $thumb_height = $thumb_width / $scale_org;
        }

        /* 创建缩略图的标志符 */
        if ($gd == 2)
        {
            $img_thumb  = imagecreatetruecolor($thumb_width, $thumb_height);
        }
        else
        {
            $img_thumb  = imagecreate($thumb_width, $thumb_height);
        }

        /* 背景颜色 */
        if (empty($bgcolor))
        {
            $bgcolor = $this->bgcolor;
        }
        $bgcolor = trim($bgcolor,"#");
        sscanf($bgcolor, "%2x%2x%2x", $red, $green, $blue);
        $clr = imagecolorallocate($img_thumb, $red, $green, $blue);
        imagefilledrectangle($img_thumb, 0, 0, $thumb_width, $thumb_height, $clr);

        if ($org_info[0] / $thumb_width > $org_info[1] / $thumb_height)
        {
            $lessen_width  = $thumb_width;
            $lessen_height  = $thumb_width / $scale_org;
        }
        else
        {
            /* 原始图片比较高，则以高度为准 */
            $lessen_width  = $thumb_height * $scale_org;
            $lessen_height = $thumb_height;
        }

        $dst_x = ($thumb_width  - $lessen_width)  / 2;
        $dst_y = ($thumb_height - $lessen_height) / 2;

        /* 将原始图片进行缩放处理 */
        if ($gd == 2)
        {
            imagecopyresampled($img_thumb, $img_org, $dst_x, $dst_y, 0, 0, $lessen_width, $lessen_height, $org_info[0], $org_info[1]);
        }
        else
        {
            imagecopyresized($img_thumb, $img_org, $dst_x, $dst_y, 0, 0, $lessen_width, $lessen_height, $org_info[0], $org_info[1]);
        }

        /* 创建当月目录 */
        if (empty($path))
        {
            $dir = SHOP_PATH . 'goods_images' . '/' . date('Ym').'/';
        }
        else
        {
            $dir = $path;
        }


        /* 如果目标目录不存在，则创建它 */
        if (!file_exists($dir))
        {
            if (!make_dir($dir))
            {
                /* 创建目录失败 */
               // $this->error_msg  = sprintf($GLOBALS['_LANG']['directory_readonly'], $dir);
               // $this->error_no   = ERR_DIRECTORY_READONLY;
                return false;
            }
        }

        /* 如果文件名为空，生成不重名随机文件名 */
        $filename = $this->unique_name($dir);

        /* 生成文件 */
        if (function_exists('imagejpeg'))
        {
            $filename .= '.jpg';
            imagejpeg($img_thumb, $dir . $filename);
        }
        elseif (function_exists('imagegif'))
        {
            $filename .= '.gif';
            imagegif($img_thumb, $dir . $filename);
        }
        elseif (function_exists('imagepng'))
        {
            $filename .= '.png';
            imagepng($img_thumb, $dir . $filename);
        }
        else
        {
          //  $this->error_msg = $GLOBALS['_LANG']['creating_failure'];
           // $this->error_no  =  ERR_NO_GD;

            return false;
        }

        imagedestroy($img_thumb);
        imagedestroy($img_org);

        //确认文件是否生成
        if (file_exists($dir . $filename))
        {
            return str_replace(SHOP_PATH, '', $dir) . $filename;
        }
        else
        {
           // $this->error_msg = $GLOBALS['_LANG']['writting_failure'];
          //  $this->error_no   = ERR_DIRECTORY_READONLY;

            return false;
        }
    }
    
    /**
     * 获得服务器上的 GD 版本
     *
     * @access      public
     * @return      int         可能的值为0，1，2
     */
    function gd_version()
    {
    	static $version = -1;
    
    	if ($version >= 0)
    	{
    		return $version;
    	}
    
    	if (!extension_loaded('gd'))
    	{
    		$version = 0;
    	}
    	else
    	{
    		// 尝试使用gd_info函数
    		if (PHP_VERSION >= '4.3')
    		{
    			if (function_exists('gd_info'))
    			{
    				$ver_info = gd_info();
    				preg_match('/\d/', $ver_info['GD Version'], $match);
    				$version = $match[0];
    			}
    			else
    			{
    				if (function_exists('imagecreatetruecolor'))
    				{
    					$version = 2;
    				}
    				elseif (function_exists('imagecreate'))
    				{
    					$version = 1;
    				}
    			}
    		}
    		else
    		{
    			if (preg_match('/phpinfo/', ini_get('disable_functions')))
    			{
    				/* 如果phpinfo被禁用，无法确定gd版本 */
    				$version = 1;
    			}
    			else
    			{
    				// 使用phpinfo函数
    				ob_start();
    				phpinfo(8);
    				$info = ob_get_contents();
    				ob_end_clean();
    				$info = stristr($info, 'gd version');
    				preg_match('/\d/', $info, $match);
    				$version = $match[0];
    			}
    		}
    	}
    
    	return $version;
    }
    
    /**
     * 根据来源文件的文件类型创建一个图像操作的标识符
     *
     * @access  public
     * @param   string      $img_file   图片文件的路径
     * @param   string      $mime_type  图片文件的文件类型
     * @return  resource    如果成功则返回图像操作标志符，反之则返回错误代码
     */
    function img_resource($img_file, $mime_type)
    {
    	switch ($mime_type)
    	{
    		case 1:
    		case 'image/gif':
    			$res = imagecreatefromgif($img_file);
    			break;
    
    		case 2:
    		case 'image/pjpeg':
    		case 'image/jpeg':
    			$res = imagecreatefromjpeg($img_file);
    			break;
    
    		case 3:
    		case 'image/x-png':
    		case 'image/png':
    			$res = imagecreatefrompng($img_file);
    			break;
    
    		default:
    			return false;
    	}
    
    	return $res;
    }
    
    /**
     * 检查图片处理能力
     *
     * @access  public
     * @param   string  $img_type   图片类型
     * @return  void
     */
    function check_img_function($img_type)
    {
    	switch ($img_type)
    	{
    		case 'image/gif':
    		case 1:
    
    			if (PHP_VERSION >= '4.3')
    			{
    				return function_exists('imagecreatefromgif');
    			}
    			else
    			{
    				return (imagetypes() & IMG_GIF) > 0;
    			}
    			break;
    
    		case 'image/pjpeg':
    		case 'image/jpeg':
    		case 2:
    			if (PHP_VERSION >= '4.3')
    			{
    				return function_exists('imagecreatefromjpeg');
    			}
    			else
    			{
    				return (imagetypes() & IMG_JPG) > 0;
    			}
    			break;
    
    		case 'image/x-png':
    		case 'image/png':
    		case 3:
    			if (PHP_VERSION >= '4.3')
    			{
    				return function_exists('imagecreatefrompng');
    			}
    			else
    			{
    				return (imagetypes() & IMG_PNG) > 0;
    			}
    			break;
    
    		default:
    			return false;
    	}
    }
	
 /**
     * 生成随机的数字串
     *
     * @author: weber liu
     * @return string
     */
    function random_filename()
    {
        $str = '';
        for($i = 0; $i < 9; $i++)
        {
            $str .= rand(0, 9);
        }

        return time() . $str;
    }

    /**
     *  生成指定目录不重名的文件名
     *
     * @access  public
     * @param   string      $dir        要检查是否有同名文件的目录
     *
     * @return  string      文件名
     */
    function unique_name($dir)
    {
        $filename = '';
        while (empty($filename))
        {
            $filename = $this->random_filename();
            if (file_exists($dir . $filename . '.jpg') || file_exists($dir . $filename . '.gif') || file_exists($dir . $filename . '.png'))
            {
                $filename = '';
            }
        }

        return $filename;
    }
    
    /**
     * 格式化商品图片名称（按目录存储）
     *
     */
    function reformat_image_name($type, $goods_id, $source_img, $position='')
    {
    	$rand_name = time() . sprintf("%03d", rand(1,999));
    	$img_ext = substr($source_img, strrpos($source_img, '.'));
    	$dir = 'goods_images';
    	$sub_dir = date('Ym', time());
    	if (!make_dir(SHOP_PATH . $dir . '/' . $sub_dir))
    	{
    		return false;
    	}
    	if (!make_dir(SHOP_PATH  . $dir . '/' . $sub_dir . '/source_img'))
    	{
    		return false;
    	}
    	if (!make_dir(SHOP_PATH . $dir . '/' . $sub_dir . '/goods_img'))
    	{
    		return false;
    	}
    	if (!make_dir(SHOP_PATH . $dir . '/' . $sub_dir . '/thumb_img'))
    	{
    		return false;
    	}
    	switch($type)
    	{
    		case 'goods':
    			$img_name = $goods_id . '_G_' . $rand_name;
    			break;
    		case 'goods_thumb':
    			$img_name = $goods_id . '_thumb_G_' . $rand_name;
    			break;
    		case 'gallery':
    			$img_name = $goods_id . '_P_' . $rand_name;
    			break;
    		case 'gallery_thumb':
    			$img_name = $goods_id . '_thumb_P_' . $rand_name;
    			break;
    	}
    	if ($position == 'thumb')
    	{
    		if ($this->move_image_file(SHOP_PATH.$source_img, SHOP_PATH.$dir.'/'.$sub_dir.'/thumb_img/'.$img_name.$img_ext))
    		{
    			return $dir.'/'.$sub_dir.'/thumb_img/'.$img_name.$img_ext;
    		}
    	}
    	else if($position == 'source')
    	{
    		if ($this->move_image_file(SHOP_PATH.$source_img, SHOP_PATH.$dir.'/'.$sub_dir.'/source_img/'.$img_name.$img_ext))
    		{
    			return $dir.'/'.$sub_dir.'/source_img/'.$img_name.$img_ext;
    		}
    	}
    	else
    	{
    		if ($this->move_image_file(SHOP_PATH.$source_img, SHOP_PATH.$dir.'/'.$sub_dir.'/goods_img/'.$img_name.$img_ext))
    		{
    			return $dir.'/'.$sub_dir.'/goods_img/'.$img_name.$img_ext;
    		}
    	}
    	return false;
    }
    
    function move_image_file($source, $dest)
    {
    	if (@copy($source, $dest))
    	{
    		@unlink($source);
    		return true;
    	}
    	return false;
    }
    
}